﻿using System;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace StringVisualizer
{
	public partial class StringVisualizer : Form
	{
		private bool _nullInd = true;

		public StringVisualizer(string Target, bool nullInd)
		{
			InitializeComponent();

			txtText.Text = Target;
			_nullInd = nullInd;
			if (!nullInd)
			{
				txtLength.Text = Target.Length.ToString("N0");
				byte[] hexBytes = System.Text.Encoding.ASCII.GetBytes(Target);
				StringBuilder hexString = new StringBuilder(Target.Length * 3);
				for (int i = 0; i < Target.Length; i++)
				{
					hexString.Append(hexBytes[i].ToString("X2") + " ");
				}
				txtHex.Text = hexString.ToString();
			}
		}

		private void chkWrap_CheckedChanged(object sender, EventArgs e)
		{
			txtText.WordWrap = chkWrap.Checked;
		}

		private void txtHex_MouseClick(object sender, MouseEventArgs e)
		{
			SelectText();
		}

		private void txtHex_KeyUp(object sender, KeyEventArgs e)
		{
			switch (e.KeyCode)
			{
				case Keys.Left:
				case Keys.Right:
				case Keys.Up:
				case Keys.Down:
				case Keys.End:
				case Keys.Home:
				case Keys.PageDown:
				case Keys.PageUp:
					SelectText();
					break;
			}
		}

		private void txtText_MouseClick(object sender, MouseEventArgs e)
		{
			SelectHex();
		}

		private void txtText_KeyUp(object sender, KeyEventArgs e)
		{
			switch (e.KeyCode)
			{
				case Keys.Left:
				case Keys.Right:
				case Keys.Up:
				case Keys.Down:
				case Keys.End:
				case Keys.Home:
				case Keys.PageDown:
				case Keys.PageUp:
					SelectHex();
					break;
			}
		}

		private void SelectHex()
		{
			if (!_nullInd && txtHex.Text.Length > 0)
			{
				int caretPos = txtText.SelectionStart;
				txtHex.SelectionStart = caretPos * 3;
				txtHex.SelectionLength = 2;
				txtHex.ScrollToCaret();
			}
		}

		private void SelectText()
		{
			if (!_nullInd && txtText.Text.Length > 0)
			{
				int caretPos = txtHex.SelectionStart;
				txtText.SelectionStart = caretPos / 3;
				txtText.SelectionLength = 1;
				txtText.ScrollToCaret();
			}
		}

	}
}
